<template>
    <!-- 归还弹窗 -->
    <el-dialog style="background: rgb(20, 37, 74);color: #fff;" v-model="props.dialogFormVisible" title="Shipping address" width="60%" :before-close="cancelRuKu"
        :close-on-click-modal=false>
        <template #header>
            <span>请确认</span>
        </template>
        <div style="color: #fff;">
            您要归还的是：<span v-for="(item, index) in rowInfo" :key="index">{{ item.bookName + ',' }}</span>
        </div>
        <div style="color: #fff;" class="store-posi">
            <span class="sp">存放位置：{{ recommendBox }}</span> <el-button type="primary" link
                @click="chooseBox">自定义位置</el-button>
        </div>
        <div style="color: #fff;">
            本次归还数量:{{ rowInfo.length }} 
        </div>
        <el-table class="my-custom-table" :data="suggestBox" border style="width: 100%" v-if="suggestBox.length > 1" :key="toggleRender">
            <el-table-column align="center" prop="cabinetName" label="推荐柜子" width="220" />
            <el-table-column align="center" prop="remainingCapacity" label="柜子容量" width="120" />
            <el-table-column align="center" label="扫码">
                <template #default="{ row }">
                    <div class="operation-btns">
                        <el-button-group>
                            <el-button type="primary" size="small" style="width: 10vw;" plain
                                @click="activeAndScan(row)">
                                {{ row.active ? '请扫码' : '点击扫码' }}
                            </el-button>
                            <el-button type="primary" size="small" plain @click="deleteCurrentScan(row)">{{
                                row.codeLength }}</el-button>
                        </el-button-group>
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="120">
                <template #default="{ row }">
                    <el-button type="text" @click="deleteRow(row)" size="small">清空</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-table class="my-custom-table" :data="suggestBox" border style="width: 100%" v-else>
            <el-table-column align="center" prop="cabinetName" label="推荐柜子" />
            <el-table-column align="center" prop="remainingCapacity" label="柜子容量" />
        </el-table>
        <template #footer>
            <div class="dialog-footer" style="display: flex;justify-content: center;">
                <el-button @click="confirmRuku">确定</el-button>
                <el-button type="primary" @click="cancelRuKu"> 取消 </el-button>
            </div>
        </template>
    </el-dialog>
    <selectBox :isShow="showBox" @choosedBox="closeBoxSelected" :rows="rowInfo" @close="closeBoxOnly"
        :isMulity="rowInfo.length > 1" />
</template>
<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import selectBox from './selectBox.vue';
import { recommendCabinet, judgeCode ,confirmReturn,definiteOpening} from '../../../../../api/index'
import { ElMessage } from 'element-plus';
const props = defineProps<{ dialogFormVisible: boolean, rowInfo: any[] }>();
const emit = defineEmits(['closeForm', 'confirmRuKu']);
let showBox = ref(false);

let toggleRender = ref(new Date().getTime());

// 打开柜信息
let rukuInfo = reactive<any>({});
watch(() => props.dialogFormVisible, (newVal) => {
    if (newVal) {
        recommend();
        rukuInfo = props.rowInfo;

    }
})

// 推荐柜子
let suggestBox = reactive<any>([]);

// 推荐柜子文字
let recommendBox = ref('');

// 扫码输入框
let input = reactive<any>({});

const chooseBox = () => {
    showBox.value = true;
}
// 确定归还
const confirmRuku = () => {
    // TODO
    // 发送归还请求
    console.log(suggestBox)
    console.log(props.rowInfo)
    const params:any = []
    props.rowInfo.forEach(item=>{
        params.push({receiveId:item.receiveId,bookId:props.rowInfo[0].bookId,bookCabinetDrawers:[{drawerId:suggestBox[0].drawerId,
            barCodes:[]       
        
        }]})
    })
    console.log(params)
    console.log(rukuInfo)
    let uniqueByReceiveId = params.reduce((acc:any, current:any) => {  
  // 检查acc中是否已经有相同的receiveId  
    if (!acc.some((item:any) => item.receiveId === current.receiveId)) {  
        // 如果没有，则添加到acc中  
        acc.push(current);  
     }  
    // 返回acc以便下一个迭代可以继续使用  
    return acc;  
    }, []); // 初始值为空数组  
  
    console.log(uniqueByReceiveId);
    uniqueByReceiveId.forEach((item:any)=>{
        rukuInfo.forEach((items:any)=>{
           if(items.receiveId==item.receiveId){
            item.bookCabinetDrawers[0].barCodes.push(items.code)
           }
        })
        
    })

    let bookReceiveVoList:any={}
    bookReceiveVoList.bookReceiveVoList=uniqueByReceiveId
    // return
    suggestBox.forEach((item: { ipAddress: any; })=>{
        definiteOpening({region:suggestBox[0].region,arrange:suggestBox[0].arrange,joint:suggestBox[0].joint,storey:suggestBox[0].storey,side:suggestBox[0].side,ipAddress:item.ipAddress}).then((res:any)=>{
            if(res.code === 200) {
                // ElMessage.success(res.msg)
            } else {
                ElMessage.error(res.msg)
            }
        })
    })
        confirmReturn(bookReceiveVoList).then((res: any) => {
            if (res.code == 200) {
                ElMessage.success('归还成功');
                emit('confirmRuKu', suggestBox);
            } else {
                ElMessage.error(res.msg);
            }
        })
    // if (suggestBox.length == 1) {
    //     // const params = { bookId: props.rowInfo[0].bookId, cabinetId: suggestBox[0].cabinetId, drawerId: suggestBox[0].drawerId };
    //     // const params = [{
    //     //     bookId: props.rowInfo[0].bookId,
    //     //     // 资料柜id
    //     //     cabinetId: suggestBox[0].cabinetId,
    //     //     // 抽屉id
    //     //     drawerId: suggestBox[0].drawerId,
    //     //     barCodes: rukuInfo.map((el: any) => {
    //     //         return el.code
    //     //     })
    //     // }]
        
    //     const params = {
    //         bookId: props.rowInfo[0].bookId,
    //         // 资料柜id
    //         // cabinetId: suggestBox[0].cabinetId,
    //         // 抽屉id
    //         // drawerId: suggestBox[0].drawerId,
    //         barCodes: rukuInfo[0].code
    //     }
    //     // 直接归还
    //     confirmAllReturn(params).then((res: any) => {
    //         if (res.code === 200) {
    //             ElMessage.success('归还成功');
    //             emit('confirmRuKu', suggestBox);
    //         } else {
    //             ElMessage.error(res.msg);
    //         }
    //     })
    // } else {
    //     let readyBox = suggestBox.filter((el: any) => el.codes.length > 0);
    //     const params = readyBox.map((el: any) => {
    //         return {
    //             bookId: props.rowInfo[0].bookId,
    //             // 资料柜id
    //             cabinetId: el.cabinetId,
    //             // 抽屉id
    //             bookCabinetDrawers:{
    //                 drawerId: el.drawerId,
    //                 barCodes: el.codes
    //             }
               
    //         }
    //     })
    //     console.log(params);

    //     confirmReturn(params).then((res: any) => {
    //         if (res.code == 200) {
    //             ElMessage.success('归还成功');
    //             emit('confirmRuKu', readyBox);
    //         } else {
    //             ElMessage.error(res.msg);
    //         }
    //     })
    //     // emit('confirmRuKu', readyBox);
    // }
}
// 取消归还
const cancelRuKu = () => {
    emit('closeForm');
}
const deleteRow = (row: any) => {
    suggestBox.splice(suggestBox.findIndex((el: any) => el.drawerId == row.drawerId), 1);
    toggleRender.value = new Date().getTime();
}
// 选中图书后
const closeBoxSelected = (val: any) => {
    const pos = JSON.parse(JSON.stringify(val));
    suggestBox = pos.map((el: any) => {
        el.codes = [];
        el.codeLength = 0;
        el.active = false;
        el.cabinetName = el.cabinetName + (el.side == '1' ? '左面' : '右面') + el.joint + '节' + el.storey + '层';
        el.orgName = props.rowInfo[0].orgName,
            el.miji = props.rowInfo[0].miji;
        return el;
    });
    recommendBox.value = pos.map((po: any) => {
        return po.cabinetName + (po.side == '1' ? '左面' : '右面') + po.joint + '节' + po.storey + '层'
    }).join(',');
    showBox.value = false
}

// 仅关闭box
const closeBoxOnly = () => {
    showBox.value = false;
}
// 查询推荐柜子
const recommend = async () => {
    let res = await recommendCabinet({ bookId: props.rowInfo[0].bookId, unWarehouseNum: props.rowInfo.length });
    if (res.data.length > 1) {
        suggestBox = res.data.map((el: any) => {
            el.orgName = props.rowInfo[0].orgName;
            el.miji = props.rowInfo[0].miji;
            return el;
        });
    } else {
        suggestBox = res.data.map((el: any) => {
            el.orgName = props.rowInfo[0].orgName;
            el.miji = props.rowInfo[0].miji;
            return el;
        });
    }
    recommendBox.value = res.data.map((el: any) => el.cabinetName).join(',');
}

// 扫码
const activeAndScan = (row: any) => {
    suggestBox.map((el: any) => {
        if (el.drawerId === row.drawerId) {
            el.active = !el.active;
        } else {
            el.active = false
        }
        toggleRender.value = new Date().getTime();
        return el;
    });
    const inputs = JSON.parse(JSON.stringify(input));
    if (Object.keys(inputs).length > 0) {
        input.removeEventListener('keyup', (e: any) => {
            getCode(e, row, '')
        });
        document.body.removeChild(input);
        input = null;
    }
    input = document.createElement('input');
    document.body.appendChild(input);
    input.style.position = 'fixed';
    input.style.width = '0';
    input.style.height = '0';
    input.style.border = '0';
    input.style.padding = '0';
    input.style.margin = '0';
    input.focus();
    input.addEventListener('keyup', (e: any) => {
        const val = input.value;
        // input.value = '';
        getCode(e, row, val)
    })
}
// 获取扫码结果，做输入事件处理
const getCode = async (e: any, row: any, val: any) => {
    if (e.keyCode === 13 || e.which === 13) {
        let tables = suggestBox.find((el: any) => el.drawerId === row.drawerId);
        if (tables.scanNUm >= tables.remainingCapacity) {
            ElMessage.error('当前柜子已满，请选择其他柜子');
        } else {
            // TODO前端暂时不做校验，直接添加
            const code = val;
            let isScaned = await judgeCode({ bookId: props.rowInfo[0].bookId, barCode: code }) as any;
            if (isScaned.code === 200) {
                if (isScaned.data) {
                    tables.codes.push(code);
                    tables.codeLength = tables.codes.length;
                    tables = Object.assign({}, tables);
                    ElMessage.success(isScaned.msg);
                    toggleRender.value = new Date().getTime();
                } else {
                    input.value = '';
                    ElMessage.error(isScaned.msg);
                }
            } else {
                input.value = '';
                ElMessage.error(isScaned.msg);
            }
        }
    }
}

// TODO
const deleteCurrentScan = (row: any) => {
    console.log(row);
    
 }

</script>
<style lang="less">
.store-posi {
    display: flex;
    align-items: center;

    .sp {
        margin-right: 10px;
    }
}
</style>